"""
pubrel 报文封装
QoS2协议的第三个报文
"""
from umq.mqtt.packet import (MqttFixedHeader, MqttPacket,
                             PackeIdVariableHeader, PUBREL)
from umq.errors import UMQException


class PubrelPacket(MqttPacket):
    """pubrec的封装"""
    @property
    def packet_id(self):
        return self.packet_id

    @packet_id.setter
    def packet_id(self, val):
        self.packet_id = val

    def __init__(self, fixed: MqttFixedHeader = None,
                 variable: PackeIdVariableHeader = None):
        if fixed is None:
            header = MqttFixedHeader(PUBREL, 0x00)
        else:
            if fixed.packet_type is not PUBREL:
                raise UMQException('Invalid packe type: {}'.format(fixed.packet_type))
            header = fixed
        super().__init__(header)
        self.variable = variable
        self.payload = None

    @classmethod
    def build(cls, packet_id: int):
        variable_header = PackeIdVariableHeader(packet_id)
        packet = PubrelPacket(variable=variable_header)
        return packet
